/**
 * @Date 2025/1/9 9:01
 * @Created by 衡盛永
 */

package org.example.deploy.service.impl;

import org.example.deploy.common.MyUserDetails;
import org.example.deploy.dto.ResultDto;
import org.example.deploy.pojo.SysUser;
import org.example.deploy.service.SgLoginService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.authentication.AuthenticationManager;
import org.example.deploy.utils.TokenUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Objects;

@Service
public class SgLoginServiceImpl implements SgLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public ResultDto login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authentication)) {
            throw new RuntimeException("用户名或密码错误");
        }
        System.out.println("sysUser:" + authentication.getPrincipal());
        //使用userid生成token
        MyUserDetails loginUser = (MyUserDetails) authentication.getPrincipal();
        String userId = loginUser.getSysUser().getId().toString();
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.put("userId", userId);
        String jwt = TokenUtil.sign(userMap);
        // authentication存入redis
        // redisCache.setCacheObject("login:" + userId, loginUser);
        // 把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResultDto(200, "登陆成功", map);
    }

    @Override
    public ResultDto logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        MyUserDetails loginUser = (MyUserDetails) authentication.getPrincipal();
        Integer userid = loginUser.getSysUser().getId();
        // redisCache.deleteObject("login:" + userid);
        return ResultDto.success("退出成功", true);
    }
}
